<template>
  <div class="q-pa-md bg-white q-mx-md">
    <div class="padding-page">
      <q-splitter
        v-model="splitterModel"
        unit="px"
        :limits="[250, 250]"
        :horizontal="smallScreen"
      >
        <template v-slot:before>
          <div>
            <div v-if="!smallScreen" class="text-center q-py-lg">
              <div class="text-h5 text-orange-7">
                {{ qtlCountData.names.length }}
              </div>
              <div>{{ t('resultPage.variantCount') }}</div>
            </div>
            <q-separator />
            <q-scroll-area
              :style="
                !smallScreen
                  ? { width: '240px', height: '100vh' }
                  : { width: '100%', height: '200px' }
              "
            >
              <q-list>
                <q-expansion-item
                  v-for="name in qtlCountData.names"
                  :key="qtlCountData.names.indexOf(name)"
                  :label="name"
                  :dense="smallScreen"
                  expand-separator
                  :default-opened="name == currentShow.name"
                >
                  <template v-slot:header>
                    <q-tooltip
                      v-if="name.length > 15"
                      anchor="top middle"
                      self="center middle"
                      >{{ name }}</q-tooltip
                    >
                    <q-item-section>
                      {{ name.length > 15 ? name.slice(0, 15) + ' ...' : name }}
                    </q-item-section>
                  </template>
                  <q-card class="transparent">
                    <q-card-actions :vertical="!smallScreen" align="center">
                      <q-btn
                        v-for="qtl in qtlCountData.summary[
                          qtlCountData.names.indexOf(name)
                        ]"
                        :key="qtl.qtl"
                        :name="name + '-' + qtl.qtl"
                        :label="rnaQTL(qtl.qtl)"
                        :class="
                          currentShow.qtl == qtl.qtl && currentShow.name == name
                            ? 'text-bold text-red-7 text-underline'
                            : null
                        "
                        :dense="smallScreen"
                        no-caps
                        flat
                        stretch
                        @click="setCurrentShow(name, qtl.qtl)"
                      >
                        &nbsp;
                        <q-badge
                          align="top"
                          rounded
                          :floating="false"
                          :color="qtl.color"
                          :label="qtl.cis + qtl.trans"
                        />
                      </q-btn>
                    </q-card-actions>
                  </q-card>
                </q-expansion-item>
              </q-list>
            </q-scroll-area>
          </div>
        </template>

        <template v-slot:after>
          <div class="q-pa-md q-gutter-lg">
            <!-- 变异的信息 -->
            <div class="row justify-between">
              <!-- 变异的信息 -->
              <div class="col-12 col-sm-4 self-center">
                <div class="q-pl-md">
                  <div class="text-subtitle1 text-bold text-primary">
                    <q-tooltip
                      v-if="currentShow.name.length > 25"
                      anchor="top middle"
                      self="center middle"
                      >{{ currentShow.name }}</q-tooltip
                    >
                    {{
                      currentShow.name.length > 25
                        ? currentShow.name.slice(0, 25) + ' ...'
                        : currentShow.name
                    }}
                  </div>
                </div>
              </div>
              <!-- QTL信息的统计信息 -->
              <div class="col-12 col-sm-6 row no-wrap justify-around">
                <div class="text-center">
                  <div class="text-subtitle1 text-bold text-teal-7">
                    {{ statistic.cancer }}
                  </div>
                  <div>{{ t('resultPage.cancer') }}</div>
                </div>
                <div class="text-center">
                  <div class="text-subtitle1 text-bold text-orange-7">
                    {{ statistic.phenotype }}
                  </div>
                  <div>
                    {{
                      Number(route.query.bytrait) === 0
                        ? t('resultPage.phenotype')
                        : t('resultPage.variant')
                    }}
                  </div>
                </div>
                <div class="text-center">
                  <div class="text-subtitle1 text-bold text-blue-7">
                    {{ statistic.cis }}
                  </div>
                  <div>Cis</div>
                </div>
                <div class="text-center">
                  <div class="text-subtitle1 text-bold text-blue-7">
                    {{ statistic.trans }}
                  </div>
                  <div>Trans</div>
                </div>
                <div class="text-center">
                  <q-toggle
                    :disable="transToggleState.disabled"
                    v-model="currentType"
                    true-value="trans"
                    false-value="cis"
                    class="transparent"
                    label="Trans"
                  />
                </div>
              </div>
            </div>
            <!-- 对应QTL的热图 -->
            <q-card v-show="!smallScreen" flat bordered class="q-pa-md">
              <div class="row">
                <span class="text-subtitle1"
                  >Heatmap for -log(FDR) of
                  <span class="text-bold text-green-6">{{
                    currentShow.qtl
                  }}</span>
                  -
                  <span class="text-bold text-red-6"
                    >{{
                      currentShow.name.length > 60
                        ? currentShow.name.slice(0, 60) + ' ...'
                        : currentShow.name
                    }}
                    <q-tooltip
                      v-if="currentShow.name.length > 60"
                      anchor="top middle"
                      self="center middle"
                      >{{ currentShow.name }}</q-tooltip
                    ></span
                  ></span
                >
              </div>
              <div class="row">
                <span class="text-body2"
                  >The heatmap shows the association significance in
                  {{ rnaQTL(currentShow.qtl) }} across different cancer types.
                </span>
              </div>
              <q-card-section>
                <HeatMap
                  :x_label="heatmapData.x_label"
                  :y_label="heatmapData.y_label"
                  :y_title="heatmapData.y_title"
                  :data="heatmapData.values"
                  :min="heatmapData.min"
                  :max="heatmapData.max"
                  :phenoType="pheno_marker_header_list[currentShow.qtl]"
                />
              </q-card-section>
            </q-card>
            <!-- 对应QTL的表格 -->
            <q-card bordered flat class="q-pa-md">
              <q-table
                ref="tableRef"
                :rows="tableData[currentType].rows"
                :columns="tableData[currentType].columns"
                :visible-columns="tableData[currentType].visible_cols"
                :dense="smallScreen"
                :filter="filter"
                :rows-per-page-label="t('resultPage.rows_per_page_label')"
                :rows-per-page-options="[10, 20, 50, 0]"
                :pagination-label="
                  (firstRowIndex, endRowIndex, totalRowsNumber) =>
                    `${firstRowIndex}~${endRowIndex} / ${totalRowsNumber}`
                "
                row-key="label"
              >
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                      style="
                        font-weight: bold;
                        font-size: 14px;
                        color: var(--q-primary);
                      "
                    >
                      {{ col.label }}
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:top-left>
                  <span class="text-subtitle1">
                    {{ t('resultPage.tableHeader') }}
                    <span class="text-bold text-green-6">{{
                      currentShow.qtl
                    }}</span>
                    -
                    <span class="text-bold text-red-6"
                      >{{
                        currentShow.name.length > 20
                          ? currentShow.name.slice(0, 20) + ' ...'
                          : currentShow.name
                      }}
                      <q-tooltip
                        v-if="currentShow.name.length > 20"
                        anchor="top middle"
                        self="center middle"
                        >{{ currentShow.name }}</q-tooltip
                      ></span
                    >
                  </span>
                </template>
                <template v-slot:top-right="props">
                  <div class="row q-gutter-x-sm">
                    <q-btn
                      flat
                      :ripple="false"
                      dense
                      :icon="
                        props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'
                      "
                      @click="props.toggleFullscreen"
                    />
                    <q-btn
                      icon="file_download"
                      no-caps
                      flat
                      :ripple="false"
                      dense
                      @click="exportTable"
                    />
                    <q-btn
                      v-if="smallScreen"
                      flat
                      :ripple="false"
                      dense
                      icon="search"
                    >
                      <q-popup-edit v-model="filter" anchor="center left">
                        <q-input
                          dense
                          flat
                          clearable
                          debounce="300"
                          v-model="filter"
                          :placeholder="t('resultPage.filter')"
                        >
                          <template v-slot:append>
                            <q-icon name="search" />
                          </template>
                        </q-input>
                      </q-popup-edit>
                    </q-btn>
                  </div>
                  <q-input
                    class="q-ml-md"
                    v-if="!smallScreen"
                    dense
                    flat
                    clearable
                    outlined
                    debounce="300"
                    v-model="filter"
                    :placeholder="t('resultPage.filter')"
                  >
                    <template v-slot:append>
                      <q-icon name="search" />
                    </template>
                  </q-input>
                </template>
                <template v-slot:body-cell-QTL_type="props">
                  <q-td class="text-left" key="QTL_type" :props="props">
                    <q-badge
                      :color="
                        qtl_color[
                          props.row.QTL_type.replace(/cis-|trans-/, '', 'gi') as qtlType
                        ]
                      "
                    >
                      {{
                        rnaQTL(
                          props.row.QTL_type.replace(/cis-|trans-/, '', 'gi')
                        )
                      }}
                    </q-badge>
                  </q-td>
                </template>
                <template v-slot:body-cell-plot="props">
                  <q-td key="plot" :props="props">
                    <q-btn
                      size="md"
                      color="primary"
                      icon="bar_chart"
                      dense
                      rounded
                      outline
                      @click="showBoxplot(props.row)"
                    >
                      <q-tooltip> Show boxplot </q-tooltip>
                    </q-btn>
                  </q-td>
                </template>
              </q-table>
            </q-card>
          </div>
        </template>
      </q-splitter>
    </div>
  </div>
  <q-dialog v-model="modalShow">
    <q-card style="width: 600px; height: 600px">
      <q-card-section>
        <BoxPlot
          :xlabel="boxPlotOptions.xlabel"
          :cancer="boxPlotOptions.cancer"
          :qtl="boxPlotOptions.qtl"
          :ylabel="boxPlotOptions.ylabel"
          :smaples="boxPlotOptions.samples"
          :data="boxPlotOptions.data"
        />
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import {
  computed,
  reactive,
  ref,
  Ref,
  watch,
  onBeforeMount,
  onMounted,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { exportFile, useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { Loading, QSpinnerHourglass } from 'quasar';

import HeatMap from 'src/components/HeatMap.vue';
import BoxPlot from 'src/components/BoxPlot.vue';

import { queryAggregate } from 'src/apis/queryAggregate';

import type { qtlCountType, qtlCountSummaryType } from 'src/interface/qtlCount';
import type { qtlType, associationType } from 'src/interface/qtlType';
import type { queryResultType } from 'src/interface/queryResult';
import type { qtlTableDataType } from 'src/interface/qtlTableData';
import type { qtlColorType } from 'src/interface/qtlColor';
import type { currentShowType } from 'src/interface/currentShowType';

import { qtlResultColumns } from 'src/model/qtlResult';
import { queryBoxplot } from 'src/apis/queryBoxplot';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();

const $q = useQuasar();
const smallScreen = computed(() => {
  return !$q.screen.gt.sm;
});

const splitterModel = ref(smallScreen.value ? 120 : 250);
const tableRef = ref();

// -------------------- 定义数据 -------------------- //

// 存放获取到的原始数据, 后续所有的数据基于此数据生成
const queryResult: queryResultType = reactive({
  cis: {
    data: [],
    list: [],
  },
  trans: {
    data: [],
    list: [],
  },
});

const heatmapData = reactive({
  x_label: [],
  y_label: [],
  y_title: '',
  values: [],
  min: 0,
  max: 0,
});

const qtl_color: qtlColorType = {
  apaQTL: 'orange-6',
  eQTL: 'red-6',
  lnceQTL: 'teal-6',
  mireQTL: 'light-green-6',
  meQTL: 'purple-6',
  sQTL: 'light-blue-6',
};
const pheno_marker_header_list = {
  apaQTL: 'APA_events',
  eQTL: 'GENE_name',
  lnceQTL: 'lncRNA_id',
  mireQTL: 'miRNA_id',
  sQTL: 'SPLICE_id',
  meQTL: 'probe_id',
};

const qtl_pheno_name: qtlColorType = {
  apaQTL: 'APA_events',
  eQTL: 'GENE_id',
  lnceQTL: 'lncRNA_id',
  mireQTL: 'miRNA_id',
  meQTL: 'probe_id',
  sQTL: 'SPLICE_id',
};

const quantityName: qtlColorType = {
  apaQTL: 'PDUI',
  eQTL: 'Expression (log2(FPKM)+1)',
  lnceQTL: 'Expression (log2(FPKM)+1)',
  mireQTL: 'Expression (log2(TPM)+1)',
  meQTL: 'Beta',
  sQTL: 'PSI',
};

const qtlCountData: qtlCountType = reactive({
  names: [],
  summary: [],
});

// 从返回的数据中提取列的信息
const tableData: qtlTableDataType = reactive({
  cis: {
    columns: [],
    visible_cols: [],
    rows: [],
    summary: {
      cancer: 0,
      phenotype: 0,
      records: 0,
    },
  },
  trans: {
    columns: [],
    visible_cols: [],
    rows: [],
    summary: {
      cancer: 0,
      phenotype: 0,
      records: 0,
    },
  },
});

const transToggleState = reactive({
  state: 'cis',
  disabled: <boolean>false,
});

const statistic = reactive({
  cancer: 0,
  phenotype: 0,
  cis: 0,
  trans: 0,
});

const currentShow: currentShowType = reactive({
  name: '',
  qtl: <qtlType>'eQTL',
});
const currentType: Ref<associationType> = ref('cis');

const qtlLists = reactive({
  name_list: Array<string>(),
  qtl_list: Array<string>(),
});

watch(
  () => currentType.value,
  () => {
    setCurrentShow(currentShow.name, currentShow.qtl, currentType.value);
  }
);

const rnaQTL = (rawName: string) => {
  if (rawName == 'lnceQTL') {
    return 'lncRNA-eQTL';
  } else if (rawName == 'mireQTL') {
    return 'miRNA-eQTL';
  } else {
    return rawName;
  }
};
const setCurrentShow = (
  name: string = qtlCountData.names[0],
  qtl: qtlType = qtlCountData.summary[0][0].qtl,
  type: associationType = 'cis'
) => {
  // console.log("setCurrentShow")
  currentShow.name = name;
  currentShow.qtl = qtl;
  // console.log(currentShow)
  // 判断当前QTL的cis和trans的数量情况
  let nameIndex = {
    cis: queryResult.cis.list.indexOf(name),
    trans: queryResult.trans.list.indexOf(name),
  };
  let hasCis = false;
  let hasTrans = false;
  if (nameIndex.cis > -1) {
    hasCis =
      queryResult.cis.data.length > 0 &&
      queryResult.cis.data[nameIndex.cis][qtl].length > 0;
  }
  if (nameIndex.trans > -1) {
    hasTrans =
      queryResult.trans.data.length > 0 &&
      queryResult.trans.data[nameIndex.trans][qtl].length > 0;
  }
  // 如果只有其中一种QTL, 则自动切换到那种QTL
  if (hasCis && hasTrans) {
    transToggleState.disabled = false;
    currentType.value = type;
  } else if (hasCis && !hasTrans) {
    transToggleState.disabled = true;
    currentType.value = 'cis';
    transToggleState.state = 'cis';
  } else if (hasTrans && !hasCis) {
    transToggleState.disabled = true;
    currentType.value = 'trans';
    transToggleState.state = 'trans';
  } else {
    //
  }
  updateQTLTableData();
  updateStatistics();
  updateHeatmapData();
};

const calculateQTLCountData = () => {
  // console.log("calculateQTLCountData")
  qtlCountData.names.length = 0;
  qtlCountData.summary.length = 0;
  let nameList: string[] = [];
  let qtlList: qtlType[] = [];
  var type: associationType;
  for (type of ['cis', 'trans'] as associationType[]) {
    for (var i = 0; i < queryResult[type].list.length; i++) {
      // 获得名字的并集
      if (nameList.indexOf(queryResult[type].list[i]) === -1) {
        nameList.push(queryResult[type].list[i]);
      }
      // 获取QTL类型的并集
      var qtlData: qtlType;
      for (qtlData in queryResult[type].data[i]) {
        if (
          queryResult[type].data[i][qtlData].length > 0 &&
          qtlList.indexOf(qtlData) === -1
        ) {
          qtlList.push(qtlData);
        }
      }
    }
  }
  nameList.sort();
  qtlList.sort();
  qtlCountData.names = nameList;
  // 开始计数
  for (var i = 0; i < nameList.length; i++) {
    // 填充各种QTL的数量
    let cisNameIndex = queryResult.cis.list.indexOf(nameList[i]);
    let transNameIndex = queryResult.trans.list.indexOf(nameList[i]);
    let tempArray: qtlCountSummaryType[] = [];
    var qtl: qtlType;
    for (qtl of qtlList) {
      let tempCis = 0;
      let tempTrans = 0;
      // 如果有cis结果
      if (
        cisNameIndex > -1 &&
        queryResult.cis.data[cisNameIndex][qtl].length > 0
      ) {
        tempCis = queryResult.cis.data[cisNameIndex][qtl].length;
      }
      if (
        transNameIndex > -1 &&
        queryResult.trans.data[transNameIndex][qtl].length > 0
      ) {
        tempTrans = queryResult.trans.data[transNameIndex][qtl].length;
      }
      if (tempCis || tempTrans) {
        tempArray.push({
          qtl: qtl,
          cis: tempCis,
          trans: tempTrans,
          color: qtl_color[qtl],
        });
      }
    }
    qtlCountData.summary.push(tempArray);
  }
  return {
    names: nameList,
    qtls: qtlList,
  };
};

const updateStatistics = () => {
  // console.log("updateStatistics")
  statistic.cancer = tableData[currentType.value].summary.cancer;
  statistic.phenotype = tableData[currentType.value].summary.phenotype;
  statistic.cis =
    qtlCountData.summary[qtlCountData.names.indexOf(currentShow.name)].find(
      (obj) => obj.qtl == currentShow.qtl
    ) === undefined
      ? 0
      : qtlCountData.summary[qtlCountData.names.indexOf(currentShow.name)].find(
          (obj) => obj.qtl == currentShow.qtl
        )?.cis;
  statistic.trans =
    qtlCountData.summary[qtlCountData.names.indexOf(currentShow.name)].find(
      (obj) => obj.qtl == currentShow.qtl
    ) === undefined
      ? 0
      : qtlCountData.summary[qtlCountData.names.indexOf(currentShow.name)].find(
          (obj) => obj.qtl == currentShow.qtl
        )?.trans;
};

const updateQTLTableData = () => {
  // console.log("updateQTLTableData")
  let qtl = currentShow.qtl;
  let type = currentType.value;
  let index = queryResult[type].list.indexOf(currentShow.name);
  let columnList = qtlResultColumns[currentShow.qtl];
  if (Number(route.query.bytrait) === 0) {
    // 如果按变异查询, 就不显示MNVid了
    columnList.find((obj) => obj.field === 'MNV_id').enabled = false;
  } else {
    columnList.find((obj) => obj.field === 'MNV_id').enabled = true;
  }
  tableData[type].columns = columnList;
  tableData[type].visible_cols = columnList
    .filter((item) => {
      return item.enabled;
    })
    .map((item) => item.name);
  tableData[type].rows = queryResult[type].data[index][qtl];
  tableData[type].summary.cancer = countTotal(
    queryResult[type].data[index][qtl],
    'cancer_type'
  );
  tableData[type].summary.phenotype = countTotal(
    queryResult[type].data[index][qtl],
    Number(route.query.bytrait) === 0
      ? qtl_pheno_name[qtl as keyof qtlColorType]
      : 'MNV_id'
  );
  tableData[type].summary.records = queryResult[type].data[index][qtl].length;
};

const updateHeatmapData = () => {
  // console.log("updateHeatmapData")
  let qtl: qtlType = currentShow.qtl;
  // y轴标签
  let phenoList: string[] = [];
  // 图标的y轴标题
  let phenoColumn: string =
    Number(route.query.bytrait) === 0
      ? pheno_marker_header_list[qtl]
      : 'MNV_id';
  // x轴标签
  let cancerList: string[] = [];
  // 图表的值
  let valueMatrix: Array<Array<number>> = [];

  let nameIndex = queryResult[currentType.value].list.indexOf(currentShow.name);
  let max = -Math.log10(
    queryResult[currentType.value].data[nameIndex][qtl][0].FDR
  ).toFixed(2);
  let min = max;
  // 第一次循环, 找出所有的癌症(x坐标)和基因或变异(y坐标)
  for (
    let recordIndex = 0;
    recordIndex < queryResult[currentType.value].data[nameIndex][qtl].length;
    recordIndex++
  ) {
    let cancer: string =
      queryResult[currentType.value].data[nameIndex][qtl][recordIndex]
        .cancer_type;
    if (cancerList.indexOf(cancer) === -1) {
      cancerList.push(cancer);
    }

    let phenotype: string =
      queryResult[currentType.value].data[nameIndex][qtl][recordIndex][
        phenoColumn
      ];
    if (phenoList.indexOf(phenotype) === -1) {
      phenoList.push(phenotype);
    }
  }
  // 排序所有的坐标轴标签
  cancerList.sort();
  phenoList.sort();
  // 第二次循环, 找出所有的数据对应的坐标和值, 并计算最大值和最小值
  for (
    let recordIndex = 0;
    recordIndex < queryResult[currentType.value].data[nameIndex][qtl].length;
    recordIndex++
  ) {
    // 计算热图的值
    let logFDR: number = -Math.log10(
      queryResult[currentType.value].data[nameIndex][qtl][recordIndex].FDR
    ).toFixed(2);
    // 计算热图的横坐标(癌症)
    let x_axis = cancerList.indexOf(
      queryResult[currentType.value].data[nameIndex][qtl][recordIndex]
        .cancer_type
    );
    // 计算热图的纵坐标(基因)
    let y_axis = phenoList.indexOf(
      queryResult[currentType.value].data[nameIndex][qtl][recordIndex][
        phenoColumn
      ]
    );
    // 求最大值
    if (logFDR >= max) {
      max = Math.ceil(logFDR);
    } else {
      min = Math.floor(logFDR);
    }

    // 找出数据
    let valueObj = [x_axis, y_axis, logFDR];
    valueMatrix.push(valueObj);
  }
  heatmapData.x_label = cancerList;
  heatmapData.y_label = phenoList;
  heatmapData.y_title = phenoColumn;
  heatmapData.values = valueMatrix;
  heatmapData.min = min;
  heatmapData.max = max;
};

const countTotal = (array: Array<object>, keyName: string) => {
  // console.log("countTotal")
  let temp: string[] = [];
  for (let obj of array) {
    if (temp.indexOf(obj[keyName]) === -1) {
      temp.push(obj[keyName]);
    }
  }
  return temp.length;
};

const pageInit = () => {
  // console.log("pageInit")
  // 显示查询到的第一个MNV的第一种QTL类型
  setCurrentShow(
    qtlCountData.names[0],
    qtlCountData.summary[0][0].qtl,
    qtlCountData.summary[0][0].cis > 0 ? 'cis' : 'trans'
  );
};

// watch(() => currentType.value, (newValue, oldValue) => {
//   updateQTLTableData()
//   updateStatistics()
//   updateHeatmapData()
// });

const filter = ref('');
const wrapCsvValue = (val, formatFn, row) => {
  let formatted = formatFn !== void 0 ? formatFn(val, row) : val;

  formatted =
    formatted === void 0 || formatted === null ? '' : String(formatted);
  formatted = formatted.split('"').join('""');
  /**
   * Excel accepts \n and \r in strings, but some other CSV parsers do not
   * Uncomment the next two lines to escape new lines
   */
  // .split('\n').join('\\n')
  // .split('\r').join('\\r')

  return `${formatted}`;
};
const exportTable = () => {
  // naive encoding to csv format
  const content = [
    qtlResultColumns[currentShow.qtl]
      .map((col) => wrapCsvValue(col.label))
      .slice(1)
      .join('\t'),
  ]
    .concat(
      tableData[currentType.value].rows.map((row) =>
        qtlResultColumns[currentShow.qtl]
          .map((col) =>
            wrapCsvValue(
              typeof col.field === 'function'
                ? col.field(row)
                : row[col.field === void 0 ? col.name : col.field],
              col.format,
              row
            )
          )
          .slice(1)
          .join('\t')
      )
    )
    .join('\r\n');
  const status = exportFile(
    `${currentShow.name}_${currentType.value}_${currentShow.qtl}`,
    content,
    'text'
  );

  if (status !== true) {
    $q.notify({
      message: 'Browser denied file download...',
      color: 'negative',
      icon: 'warning',
    });
  }
};

onBeforeMount(() => {
  // console.log("onBeforeMount")
  Loading.show({
    message: 'Searching for cis-QTLs......',
    spinner: QSpinnerHourglass,
    spinnerSize: 80,
    delay: 0,
  });
  // 只请求一次cis和一次trans
  queryAggregate({
    query: String(route.query.query),
    bypos: Number(route.query.bypos) as 0 | 1,
    bytrait: Number(route.query.bytrait) as 0 | 1,
    trans: 0,
  })
    .then((response) => {
      queryResult.cis.list = response.data.list;
      queryResult.cis.data = response.data.data;
      if (response.data.list.length > 0) {
        Loading.hide();
        Loading.show({
          message: 'Searching for trans-QTLs......',
          spinner: QSpinnerHourglass,
          spinnerSize: 80,
        });
      } else {
        Loading.hide();
        Loading.show({
          message: 'No cis data, now searching for trans......',
          spinner: QSpinnerHourglass,
          spinnerSize: 80,
        });
        // currentType.value = 'trans';
      }
      return queryAggregate({
        query: String(route.query.query),
        bypos: Number(route.query.bypos) as 0 | 1,
        bytrait: Number(route.query.bytrait) as 0 | 1,
        trans: 1,
      });
    })
    .then((response) => {
      queryResult.trans.list = response.data.list;
      queryResult.trans.data = response.data.data;
      if (response.data.list.length > 0) {
        Loading.hide();
      } else {
        Loading.hide();
      }
    })
    .catch((error) => {
      Loading.hide();
      $q.dialog({
        title: 'Error',
        message: `${error}`,
      })
        .onOk(() => {
          router.push({
            name: 'IndexPage',
          });
        })
        .onCancel(() => {
          // console.log('Cancel')
        })
        .onDismiss(() => {
          // console.log('I am triggered on both OK and Cancel')
        });
    })
    .finally(() => {
      if (
        queryResult.cis.list.length > 0 ||
        queryResult.trans.list.length > 0
      ) {
        let listData = calculateQTLCountData();
        qtlLists.name_list = listData.names;
        qtlLists.qtl_list = listData.qtls;
        pageInit();
      } else {
        qtlLists.name_list = [];
        qtlLists.qtl_list = [];
        $q.dialog({
          title: 'Warning',
          message: 'No results found, please try another',
        })
          .onOk(() => {
            router.push({
              name: 'IndexPage',
            });
          })
          .onCancel(() => {
            // console.log('Cancel')
          })
          .onDismiss(() => {
            // console.log('I am triggered on both OK and Cancel')
          });
      }
    });
});

onMounted(() => {
  tableRef.value.sort('FDR')
});

const modalShow = ref(false);
const boxPlotOptions = reactive({
  xlabel: '',
  cancer: '',
  qtl: '',
  ylabel: '',
  samples: ['0', '0', '0'],
  data: [[], [], []],
});

const filterBoxPlotData = (data) => {
  let emptyPosition = data.sample.indexOf(0);
  if (emptyPosition > -1) {
    data.data.splice(emptyPosition, 1);
    data.genotype.splice(emptyPosition, 1);
    data.sample.splice(emptyPosition, 1);
    return {
      data: data.data,
      genotype: data.genotype,
      sample: data.sample,
    };
  } else {
    return {
      data: data.data,
      genotype: data.genotype,
      sample: data.sample,
    };
  }
};

const showBoxplot = (params) => {
  queryBoxplot({
    MNV_id: params.MNV_id,
    cancer_type: params.cancer_type,
    QTL_type: params.QTL_type,
    phenotype:
      params[
        qtl_pheno_name[
          params.QTL_type.replace(/cis-|trans-/, '', 'gi') as qtlType
        ]
      ],
  }).then((response) => {
    boxPlotOptions.ylabel = `${quantityName[currentShow.qtl]} of ${
      params[pheno_marker_header_list[currentShow.qtl]]
    }`;
    boxPlotOptions.xlabel = `Genotype of \n${response.data.MNV_id}`;
    boxPlotOptions.cancer = response.data.cancer_type;
    boxPlotOptions.qtl = response.data.QTL_type;
    let filteredData = filterBoxPlotData(response.data);
    boxPlotOptions.samples = filteredData.sample;
    boxPlotOptions.data = filteredData.data;
    modalShow.value = true;
  });
};
</script>

<style lang="scss"></style>
